package com.wchat.converter;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sun.org.apache.bcel.internal.generic.GOTO;
import com.wchat.dataobject.OrderDetail;
import com.wchat.dto.CartDto;
import com.wchat.dto.OrderDto;
import com.wchat.enums.ResultEnum;
import com.wchat.exceptions.SellException;
import com.wchat.form.OrderForm;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yangtianrui on 17/8/12.
 */
@Slf4j
public class OrderFrom2OrderDtoConverter {

    public static OrderDto converter(OrderForm orderForm)
    {
        Gson gson = new Gson();
        OrderDto orderDto = new OrderDto();
        orderDto.setBuyerName(orderForm.getName());
        orderDto.setBuyerOpenid(orderForm.getOpenid());
        orderDto.setBuyerAddress(orderForm.getAddress());
        orderDto.setBuyerPhone(orderForm.getPhone());
        //  之所以不用BeanUtils 是因为对象属性之间的名字 对应不上  一个是buyerNmae  一个是name等这样的类型
        // 利用Google的gson 把json 格式转化为list   注意异常的捕获和抛出
        List<OrderDetail> orderDetailList = new ArrayList<>();
        try {
       orderDetailList = gson.fromJson(orderForm.getItems(),new TypeToken<List<OrderDetail>>(){}.getType());
        }catch (Exception e)
        {
            log.error("[对象转换] 错误 ,String{}",orderForm.getItems());
            throw new SellException(ResultEnum.PARAM_ERROR);
        }
        orderDto.setOrderDetails(orderDetailList);
        return  orderDto;
    }
}
